package androidvn.xenforo.fourums;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import android.widget.EditText;
import android.widget.Toast;
import androidvn.xenforo.fourums.R;
import androidvn.xenforo.fourums.widget.JsonParser;

public class AuthenticationFragment extends DialogFragment {
	JsonParser jsonParser = new JsonParser();
	ProgressDialog pDialog;

	// Login
	private static String loginURL = "http://android.vn/api.php?action=authenticate";
	private static final String TAG_HASH = "hash";
	private static final String TAG_ERROR = "error";
	private static final String TAG_MESSAGE = "message";

	private JSONObject jObj;
	EditText etUsername, etPassword;

	// setOnLoginListener communicator;
	//
	// @Override
	// public void onAttach(Activity activity) {
	// super.onAttach(activity);
	// communicator = (setOnLoginListener) activity;
	// }

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		LayoutInflater inflater = getActivity().getLayoutInflater();
		View view = inflater.inflate(R.layout.authentication_layout, null);
		etUsername = (EditText) view.findViewById(R.id.etUsername);
		etPassword = (EditText) view.findViewById(R.id.etPassword);

		builder.setView(view);
		builder.setCancelable(false);
		builder.setTitle("Đăng nhập");
		builder.setNegativeButton("Thoát", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dismiss();
			}
		});
		builder.setPositiveButton("Login", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				if (etUsername.getText().toString().trim().length() == 0) {
					Toast.makeText(getActivity(), "Username is empty",
							Toast.LENGTH_LONG).show();
				} else if (etPassword.getText().toString().trim().length() == 0) {
					Toast.makeText(getActivity(), "Password is empty",
							Toast.LENGTH_LONG).show();
				} else if (etUsername.getText().toString().trim().length() > 0
						&& etPassword.getText().toString().trim().length() > 0) {
					new loadData().execute();

				}
				dismiss();

			}
		});
		Dialog dialog = builder.create();
		return dialog;
	}

	class loadData extends AsyncTask<String, String, String> {
		String hash = "";
		String errorId = "";
		String errorMessage = "";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Authenticating ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... arg0) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();

			params.add(new BasicNameValuePair("username", etUsername.getText()
					.toString()));
			params.add(new BasicNameValuePair("password", etPassword.getText()
					.toString()));
			jObj = jsonParser.makeHttpRequest(loginURL, "GET", params);

			// Log.d("jObj", "" + jObj);
			if (jObj != null) {
				try {
					errorId = jObj.getString(TAG_ERROR);
					errorMessage = jObj.getString(TAG_MESSAGE);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				try {
					hash = jObj.getString(TAG_HASH);
					// Log.d(TAG_HASH, hash);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(String... values) {

			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {

					if (errorId.trim().length() > 0
							&& hash.trim().length() == 0) {
						Global.loginStatus = false;
						Global.userHash = "";
						switch (Integer.valueOf(errorId)) {
						case 1:
							Toast.makeText(
									getActivity().getApplicationContext(),
									errorMessage, Toast.LENGTH_LONG).show();
							break;
						case 3:
							Toast.makeText(
									getActivity().getApplicationContext(),
									errorMessage, Toast.LENGTH_LONG).show();
							break;
						case 4:
							Toast.makeText(
									getActivity().getApplicationContext(),
									errorMessage, Toast.LENGTH_LONG).show();
							break;
						case 5:
							Toast.makeText(
									getActivity().getApplicationContext(),
									errorMessage, Toast.LENGTH_LONG).show();
							break;
						}
					} else {
						Toast.makeText(getActivity().getApplicationContext(),
								"Login successful", Toast.LENGTH_SHORT).show();
					}

				}
			});
		}

		@Override
		protected void onPostExecute(String result) {
			pDialog.dismiss();

			if (hash.trim().length() > 0) {
				Global.userHash = hash;
				Global.userName = etUsername.getText().toString();
				Global.loginStatus = true;

			}
			Log.d("user info", etUsername.getText().toString() + " / "
					+ Global.userHash);

			// Log.d("error id", errorId + " " + errorMessage);
		}
	}

}
